from flask import render_template, redirect, url_for, flash, request, session, jsonify, current_app, send_from_directory
from . import admin_bp
from functools import wraps
from pymongo import MongoClient
from bson import ObjectId
import datetime
import json
import os
import uuid
from werkzeug.utils import secure_filename

# MongoDB connection
client = MongoClient('mongodb://localhost:27017/')
db = client['scpy']
users_collection = db['users']
questions_collection = db['questions']
exams_collection = db['exams']  # 添加试卷集合
submissions_collection = db['submissions']  # 添加提交集合

# 配置上传文件的目录和允许的扩展名
UPLOAD_FOLDER = 'static/uploads/questions'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# 添加模板全局变量
@admin_bp.app_template_global()
def chr_function(num):
    return chr(num)

def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        user = session.get('user', {})
        if not user.get('is_authenticated') or not user.get('is_admin', False):
            flash('请先登录管理员账号', 'warning')
            return redirect(url_for('admin.login'))
        return f(*args, **kwargs)
    return decorated_function

@admin_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        # TODO: 实现管理员验证逻辑
        if username == 'admin' and password == 'admin':  # 临时的管理员验证
            session['user'] = {'username': username, 'is_authenticated': True, 'is_admin': True}
            flash('登录成功！', 'success')
            return redirect(url_for('admin.dashboard'))
        flash('用户名或密码错误！', 'danger')
    return render_template('admin/login.html')

@admin_bp.route('/dashboard')
@admin_required
def dashboard():
    return render_template('admin/dashboard.html')

@admin_bp.route('/users')
@admin_required
def user_list():
    # 获取分页参数
    page = request.args.get('page', 1, type=int)
    per_page = 10
    skip = (page - 1) * per_page
    
    # 获取搜索参数
    search = request.args.get('search', '')
    
    # 构建查询条件
    query = {}
    if search:
        query['username'] = {'$regex': search, '$options': 'i'}
    
    # 获取用户总数
    total_users = users_collection.count_documents(query)
    total_pages = (total_users + per_page - 1) // per_page
    
    # 获取用户列表
    users = users_collection.find(query).skip(skip).limit(per_page)
    
    return render_template('admin/user_list.html',
                         users=users,
                         current_page=page,
                         total_pages=total_pages,
                         search=search)

@admin_bp.route('/users/create', methods=['GET', 'POST'])
@admin_required
def user_create():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        email = request.form.get('email')
        grade = request.form.get('grade')
        is_admin = request.form.get('is_admin') == 'on'
        
        if users_collection.find_one({'username': username}):
            flash('用户名已存在！', 'danger')
        else:
            users_collection.insert_one({
                'username': username,
                'password': password,  # 注意：实际应用中应该对密码进行加密
                'email': email,
                'grade': grade,
                'is_admin': is_admin
            })
            flash('用户创建成功！', 'success')
            return redirect(url_for('admin.user_list'))
            
    return render_template('admin/user_form.html', user=None)

@admin_bp.route('/users/edit/<user_id>', methods=['GET', 'POST'])
@admin_required
def user_edit(user_id):
    user = users_collection.find_one({'_id': ObjectId(user_id)})
    if not user:
        flash('用户不存在！', 'danger')
        return redirect(url_for('admin.user_list'))
        
    if request.method == 'POST':
        username = request.form.get('username')
        email = request.form.get('email')
        grade = request.form.get('grade')
        is_admin = request.form.get('is_admin') == 'on'
        
        # 检查用户名是否已存在（排除当前用户）
        existing_user = users_collection.find_one({
            'username': username,
            '_id': {'$ne': ObjectId(user_id)}
        })
        if existing_user:
            flash('用户名已存在！', 'danger')
        else:
            update_data = {
                'username': username,
                'email': email,
                'grade': grade,
                'is_admin': is_admin
            }
            
            # 如果提供了新密码，则更新密码
            new_password = request.form.get('password')
            if new_password:
                update_data['password'] = new_password  # 注意：实际应用中应该对密码进行加密
                
            users_collection.update_one(
                {'_id': ObjectId(user_id)},
                {'$set': update_data}
            )
            flash('用户信息更新成功！', 'success')
            return redirect(url_for('admin.user_list'))
            
    return render_template('admin/user_form.html', user=user)

@admin_bp.route('/users/delete/<user_id>', methods=['POST'])
@admin_required
def user_delete(user_id):
    result = users_collection.delete_one({'_id': ObjectId(user_id)})
    if result.deleted_count:
        flash('用户删除成功！', 'success')
    else:
        flash('用户不存在！', 'danger')
    return redirect(url_for('admin.user_list'))

@admin_bp.route('/questions')
@admin_required
def question_list():
    # 获取分页参数
    page = request.args.get('page', 1, type=int)
    per_page = 10
    skip = (page - 1) * per_page
    
    # 获取筛选参数
    question_type = request.args.get('type', '')
    search = request.args.get('search', '')
    
    # 构建查询条件
    query = {}
    if question_type:
        query['type'] = question_type
    if search:
        query['title'] = {'$regex': search, '$options': 'i'}
    
    # 获取试题总数
    total_questions = questions_collection.count_documents(query)
    total_pages = (total_questions + per_page - 1) // per_page
    
    # 获取试题列表
    questions = questions_collection.find(query).skip(skip).limit(per_page)
    
    return render_template('admin/question_list.html',
                         questions=questions,
                         current_page=page,
                         total_pages=total_pages,
                         search=search,
                         question_type=question_type)

@admin_bp.route('/questions/create', methods=['GET', 'POST'])
@admin_required
def question_create():
    if request.method == 'POST':
        question_type = request.form.get('type')
        title = request.form.get('title')
        options = []
        correct_answers = []
        
        if question_type in ['single', 'multiple']:
            # 处理选项
            for i in range(4):  # 假设有4个选项
                option = request.form.get(f'option_{i}')
                if option:
                    options.append(option)
            
            # 处理正确答案
            if question_type == 'single':
                correct_answer = request.form.get('correct_answer')
                if correct_answer is not None:
                    correct_answers = [int(correct_answer)]
            else:  # multiple
                for i in range(len(options)):
                    if request.form.get(f'correct_answer_{i}'):
                        correct_answers.append(i)
        else:  # boolean
            correct_answers = [request.form.get('correct_answer') == 'true']
        
        # 创建试题
        question = {
            'type': question_type,
            'title': title,
            'options': options if question_type in ['single', 'multiple'] else [],
            'correct_answers': correct_answers
        }
        
        questions_collection.insert_one(question)
        flash('试题创建成功！', 'success')
        return redirect(url_for('admin.question_list'))
        
    return render_template('admin/question_form.html', question=None)

@admin_bp.route('/questions/edit/<question_id>', methods=['GET', 'POST'])
@admin_required
def question_edit(question_id):
    question = questions_collection.find_one({'_id': ObjectId(question_id)})
    if not question:
        flash('试题不存在！', 'danger')
        return redirect(url_for('admin.question_list'))
        
    if request.method == 'POST':
        question_type = request.form.get('type')
        title = request.form.get('title')
        options = []
        correct_answers = []
        
        if question_type in ['single', 'multiple']:
            # 处理选项
            for i in range(4):
                option = request.form.get(f'option_{i}')
                if option:
                    options.append(option)
            
            # 处理正确答案
            if question_type == 'single':
                correct_answer = request.form.get('correct_answer')
                if correct_answer is not None:
                    correct_answers = [int(correct_answer)]
            else:  # multiple
                for i in range(len(options)):
                    if request.form.get(f'correct_answer_{i}'):
                        correct_answers.append(i)
        else:  # boolean
            correct_answers = [request.form.get('correct_answer') == 'true']
        
        # 更新试题
        questions_collection.update_one(
            {'_id': ObjectId(question_id)},
            {'$set': {
                'type': question_type,
                'title': title,
                'options': options if question_type in ['single', 'multiple'] else [],
                'correct_answers': correct_answers
            }}
        )
        flash('试题更新成功！', 'success')
        return redirect(url_for('admin.question_list'))
        
    return render_template('admin/question_form.html', question=question)

@admin_bp.route('/questions/delete/<question_id>', methods=['POST'])
@admin_required
def question_delete(question_id):
    result = questions_collection.delete_one({'_id': ObjectId(question_id)})
    if result.deleted_count:
        flash('试题删除成功！', 'success')
    else:
        flash('试题不存在！', 'danger')
    return redirect(url_for('admin.question_list'))

@admin_bp.route('/exams')
@admin_required
def exam_list():
    # 获取分页参数
    page = request.args.get('page', 1, type=int)
    per_page = 10
    skip = (page - 1) * per_page
    
    # 获取筛选参数
    subject = request.args.get('subject', '')
    search = request.args.get('search', '')
    
    # 构建查询条件
    query = {}
    if subject:
        query['subject'] = subject
    if search:
        query['name'] = {'$regex': search, '$options': 'i'}
    
    # 获取试卷总数
    total_exams = exams_collection.count_documents(query)
    total_pages = (total_exams + per_page - 1) // per_page
    
    # 获取试卷列表
    exams = exams_collection.find(query).sort('created_at', -1).skip(skip).limit(per_page)
    
    return render_template('admin/exam_list.html',
                         exams=exams,
                         current_page=page,
                         total_pages=total_pages,
                         search=search,
                         subject=subject)

@admin_bp.route('/exams/create', methods=['GET', 'POST'])
@admin_required
def exam_create():
    if request.method == 'POST':
        try:
            # 调试输出
            print("Form data:", request.form)
            print("Files:", request.files)
            
            # 获取基本信息
            name = request.form.get('name')
            subject = request.form.get('subject')
            
            # 安全获取难度
            try:
                difficulty = int(request.form.get('difficulty', 1))
            except ValueError:
                difficulty = 1  # 默认难度为1
            
            # 验证基本信息
            if not name or not subject:
                flash('试卷名称和科目不能为空！', 'danger')
                return redirect(url_for('admin.exam_create'))
            
            # 处理试题数据
            questions = []
            
            # 获取题目数量（通过type字段判断）
            question_count = 0
            while request.form.get(f'questions[{question_count}][type]'):
                question_count += 1
            
            if question_count == 0:
                flash('试卷至少需要一道题目！', 'danger')
                return redirect(url_for('admin.exam_create'))
            
            # 处理每个题目
            for i in range(question_count):
                question_type = request.form.get(f'questions[{i}][type]')
                title = request.form.get(f'questions[{i}][title]')
                
                if not title:
                    flash(f'第 {i+1} 题的题目内容不能为空！', 'danger')
                    return redirect(url_for('admin.exam_create'))
                
                # 初始化题目对象
                question = {
                    'type': question_type,
                    'title': title,
                    'has_image': False,
                    'image_path': None
                }
                
                # 处理图片上传
                if f'questions[{i}][image]' in request.files:
                    file = request.files[f'questions[{i}][image]']
                    if file and file.filename != '':
                        if allowed_file(file.filename):
                            # 生成安全的文件名
                            filename = secure_filename(file.filename)
                            # 使用UUID生成唯一文件名
                            unique_filename = f"{uuid.uuid4()}_{filename}"
                            # 确保上传目录存在
                            os.makedirs(UPLOAD_FOLDER, exist_ok=True)
                            # 保存文件
                            file_path = os.path.join(UPLOAD_FOLDER, unique_filename)
                            file.save(file_path)
                            # 更新题目信息
                            question['has_image'] = True
                            question['image_path'] = f"/{file_path.replace(os.sep, '/')}"
                        else:
                            flash(f'第 {i+1} 题的图片格式不支持！', 'danger')
                            return redirect(url_for('admin.exam_create'))
                
                if question_type in ['single', 'multiple']:
                    # 获取当前题目的选项
                    options = []
                    option_count = 0
                    while True:
                        option = request.form.get(f'questions[{i}][options][{option_count}]')
                        if option is None:
                            break
                        options.append(option)
                        option_count += 1
                    
                    # 验证选项
                    if not all(options):
                        flash(f'第 {i+1} 题的选项不能为空！', 'danger')
                        return redirect(url_for('admin.exam_create'))
                    
                    # 获取正确答案
                    correct_answers = []
                    if question_type == 'single':
                        correct_answer = request.form.get(f'questions[{i}][correct_answers][]')
                        if correct_answer is None or correct_answer == '':
                            flash(f'第 {i+1} 题必须选择一个正确答案！', 'danger')
                            return redirect(url_for('admin.exam_create'))
                        
                        # 处理可能的数据类型问题
                        if correct_answer == 'on':
                            # 如果值是'on'，可能是第一个选项被选中
                            correct_answers = [0]
                        else:
                            try:
                                correct_answers = [int(correct_answer)]
                            except ValueError:
                                flash(f'第 {i+1} 题的答案格式不正确！值: {correct_answer}', 'danger')
                                return redirect(url_for('admin.exam_create'))
                    else:  # multiple
                        correct_answers_raw = request.form.getlist(f'questions[{i}][correct_answers][]')
                        if not correct_answers_raw:
                            flash(f'第 {i+1} 题必须至少选择一个正确答案！', 'danger')
                            return redirect(url_for('admin.exam_create'))
                        
                        for ans in correct_answers_raw:
                            if ans == 'on':
                                # 如果值是'on'，可能是第一个选项被选中
                                if 0 not in correct_answers:
                                    correct_answers.append(0)
                            else:
                                try:
                                    correct_answers.append(int(ans))
                                except ValueError:
                                    flash(f'第 {i+1} 题的答案格式不正确！值: {ans}', 'danger')
                                    return redirect(url_for('admin.exam_create'))
                    
                    question['options'] = options
                    question['correct_answers'] = correct_answers
                
                else:  # boolean
                    correct_answer = request.form.get(f'questions[{i}][correct_answer]')
                    if not correct_answer:
                        flash(f'第 {i+1} 题必须选择正确答案！', 'danger')
                        return redirect(url_for('admin.exam_create'))
                    
                    question['correct_answers'] = [correct_answer == 'true']
                
                questions.append(question)
            
            # 创建试卷
            exam = {
                'name': name,
                'subject': subject,
                'difficulty': difficulty,
                'questions': questions,
                'created_at': datetime.datetime.now().strftime('%Y-%m-%d %H:%M'),
                'updated_at': datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
            }
            
            result = exams_collection.insert_one(exam)
            flash('试卷创建成功！', 'success')
            return redirect(url_for('admin.exam_list'))
            
        except Exception as e:
            flash(f'创建试卷失败：{str(e)}', 'danger')
            return redirect(url_for('admin.exam_create'))
    
    # GET请求
    return render_template('admin/exam_form.html')

@admin_bp.route('/exams/edit/<exam_id>', methods=['GET', 'POST'])
@admin_required
def exam_edit(exam_id):
    try:
        # 确保在任何流程之前获取试卷
        exam = exams_collection.find_one({'_id': ObjectId(exam_id)})
        if not exam:
            flash('试卷不存在！', 'danger')
            return redirect(url_for('admin.exam_list'))
            
        if request.method == 'POST':
            try:
                # 调试输出
                print("编辑表单数据:", request.form)
                print("编辑文件:", request.files)
                
                # 获取基本信息
                name = request.form.get('name')
                subject = request.form.get('subject')
                
                # 安全获取难度
                try:
                    difficulty = int(request.form.get('difficulty', 1))
                except ValueError:
                    difficulty = 1  # 默认难度为1
                
                # 验证基本信息
                if not name or not subject:
                    flash('试卷名称和科目不能为空！', 'danger')
                    return redirect(url_for('admin.exam_edit', exam_id=exam_id))
                
                # 处理试题数据
                questions = []
                
                # 获取题目数量（通过type字段判断）
                question_count = 0
                while request.form.get(f'questions[{question_count}][type]'):
                    question_count += 1
                
                if question_count == 0:
                    flash('试卷至少需要一道题目！', 'danger')
                    return redirect(url_for('admin.exam_edit', exam_id=exam_id))
                
                # 处理每个题目
                for i in range(question_count):
                    question_type = request.form.get(f'questions[{i}][type]')
                    title = request.form.get(f'questions[{i}][title]')
                    
                    if not title:
                        flash(f'第 {i+1} 题的题目内容不能为空！', 'danger')
                        return redirect(url_for('admin.exam_edit', exam_id=exam_id))
                    
                    # 获取原题目信息（如果存在）
                    original_question = None
                    if i < len(exam['questions']):
                        original_question = exam['questions'][i]
                    
                    # 处理图片上传和图片状态
                    has_image = request.form.get(f'questions[{i}][has_image]') == 'true'
                    original_image_path = request.form.get(f'questions[{i}][original_image_path]')
                    
                    # 设置初始图片状态
                    question = {
                        'type': question_type,
                        'title': title,
                        'has_image': has_image,
                        'image_path': None
                    }
                    
                    if has_image and original_image_path:
                        question['image_path'] = original_image_path
                    
                    # 处理新上传的图片
                    if f'questions[{i}][image]' in request.files:
                        file = request.files[f'questions[{i}][image]']
                        if file and file.filename != '':
                            if allowed_file(file.filename):
                                # 如果有旧图片，可以考虑删除
                                if original_question and original_question.get('has_image') and original_question.get('image_path'):
                                    old_path = original_question['image_path'].lstrip('/')
                                    if os.path.exists(old_path):
                                        try:
                                            os.remove(old_path)
                                        except:
                                            pass  # 忽略删除错误
                                
                                # 生成安全的文件名
                                filename = secure_filename(file.filename)
                                unique_filename = f"{uuid.uuid4()}_{filename}"
                                os.makedirs(UPLOAD_FOLDER, exist_ok=True)
                                file_path = os.path.join(UPLOAD_FOLDER, unique_filename)
                                file.save(file_path)
                                question['has_image'] = True
                                question['image_path'] = f"/{file_path.replace(os.sep, '/')}"
                            else:
                                flash(f'第 {i+1} 题的图片格式不支持！', 'danger')
                                return redirect(url_for('admin.exam_edit', exam_id=exam_id))
                    
                    if question_type in ['single', 'multiple']:
                        # 获取当前题目的选项
                        options = []
                        option_count = 0
                        while True:
                            option = request.form.get(f'questions[{i}][options][{option_count}]')
                            if option is None:
                                break
                            options.append(option)
                            option_count += 1
                        
                        # 验证选项
                        if not all(options):
                            flash(f'第 {i+1} 题的选项不能为空！', 'danger')
                            return redirect(url_for('admin.exam_edit', exam_id=exam_id))
                        
                        # 获取正确答案
                        correct_answers = []
                        if question_type == 'single':
                            correct_answer = request.form.get(f'questions[{i}][correct_answers][]')
                            if correct_answer is None or correct_answer == '':
                                flash(f'第 {i+1} 题必须选择一个正确答案！', 'danger')
                                return redirect(url_for('admin.exam_edit', exam_id=exam_id))
                            
                            # 处理可能的数据类型问题
                            if correct_answer == 'on':
                                # 如果值是'on'，可能是第一个选项被选中
                                correct_answers = [0]
                            else:
                                try:
                                    correct_answers = [int(correct_answer)]
                                except ValueError:
                                    flash(f'第 {i+1} 题的答案格式不正确！值: {correct_answer}', 'danger')
                                    return redirect(url_for('admin.exam_edit', exam_id=exam_id))
                        else:  # multiple
                            correct_answers_raw = request.form.getlist(f'questions[{i}][correct_answers][]')
                            if not correct_answers_raw:
                                flash(f'第 {i+1} 题必须至少选择一个正确答案！', 'danger')
                                return redirect(url_for('admin.exam_edit', exam_id=exam_id))
                            
                            for ans in correct_answers_raw:
                                if ans == 'on':
                                    # 如果值是'on'，可能是第一个选项被选中
                                    if 0 not in correct_answers:
                                        correct_answers.append(0)
                                else:
                                    try:
                                        correct_answers.append(int(ans))
                                    except ValueError:
                                        flash(f'第 {i+1} 题的答案格式不正确！值: {ans}', 'danger')
                                        return redirect(url_for('admin.exam_edit', exam_id=exam_id))
                        
                        question['options'] = options
                        question['correct_answers'] = correct_answers
                    
                    else:  # boolean
                        correct_answer = request.form.get(f'questions[{i}][correct_answer]')
                        if not correct_answer:
                            flash(f'第 {i+1} 题必须选择正确答案！', 'danger')
                            return redirect(url_for('admin.exam_edit', exam_id=exam_id))
                        
                        question['correct_answers'] = [correct_answer == 'true']
                    
                    questions.append(question)
                
                # 更新试卷
                exams_collection.update_one(
                    {'_id': ObjectId(exam_id)},
                    {'$set': {
                        'name': name,
                        'subject': subject,
                        'difficulty': difficulty,
                        'questions': questions,
                        'updated_at': datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
                    }}
                )
                flash('试卷更新成功！', 'success')
                return redirect(url_for('admin.exam_list'))
                
            except Exception as e:
                flash(f'更新试卷时出错：{str(e)}', 'danger')
                return redirect(url_for('admin.exam_edit', exam_id=exam_id))
        
        # GET 请求展示表单
        return render_template('admin/exam_form.html', exam=exam)
        
    except Exception as e:
        flash(f'加载试卷时出错：{str(e)}', 'danger')
        return redirect(url_for('admin.exam_list'))

@admin_bp.route('/exams/delete/<exam_id>', methods=['POST'])
@admin_required
def exam_delete(exam_id):
    result = exams_collection.delete_one({'_id': ObjectId(exam_id)})
    if result.deleted_count:
        flash('试卷删除成功！', 'success')
    else:
        flash('试卷不存在！', 'danger')
    return redirect(url_for('admin.exam_list'))

# 查看试卷
@admin_bp.route('/exams/view/<exam_id>')
@admin_required
def exam_view(exam_id):
    try:
        # 获取试卷信息
        exam = exams_collection.find_one({'_id': ObjectId(exam_id)})
        if not exam:
            flash('试卷不存在或已删除', 'danger')
            return redirect(url_for('admin.exam_list'))
        
        return render_template('admin/exam_view.html', exam=exam)
    except Exception as e:
        flash(f'查看试卷时出错: {str(e)}', 'danger')
        return redirect(url_for('admin.exam_list'))

# 查看单个题目
@admin_bp.route('/exams/question_view/<exam_id>/<int:question_index>')
@admin_required
def question_view(exam_id, question_index):
    try:
        # 获取试卷信息
        exam = exams_collection.find_one({'_id': ObjectId(exam_id)})
        if not exam:
            flash('试卷不存在或已删除', 'danger')
            return redirect(url_for('admin.exam_list'))
        
        # 检查题目索引是否有效
        if question_index < 0 or question_index >= len(exam.get('questions', [])):
            flash('题目不存在', 'danger')
            return redirect(url_for('admin.exam_view', exam_id=exam_id))
        
        question = exam['questions'][question_index]
        
        return render_template(
            'admin/question_view.html', 
            exam=exam, 
            question=question, 
            question_index=question_index,
            total_questions=len(exam.get('questions', []))
        )
    except Exception as e:
        flash(f'查看题目时出错: {str(e)}', 'danger')
        return redirect(url_for('admin.exam_view', exam_id=exam_id))

@admin_bp.route('/test_management')
@admin_required
def test_management():
    # 获取筛选参数
    student_name = request.args.get('student_name', '')
    school = request.args.get('school', '')
    
    # 构建查询条件
    query = {}
    if student_name:
        query['student_name'] = {'$regex': student_name, '$options': 'i'}  # 不区分大小写的模糊查询
    if school:
        query['school'] = school
    
    # 查询数据并按提交时间降序排序
    submissions = submissions_collection.find(query).sort('submit_time', -1)
    
    return render_template('admin/test_management.html', submissions=submissions)

@admin_bp.route('/test_detail/<exam_id>/<submission_id>')
@admin_required
def test_detail(exam_id, submission_id):
    try:
        # 获取试卷信息
        exam = exams_collection.find_one({'_id': ObjectId(exam_id)})
        if not exam:
            flash('试卷不存在', 'danger')
            return redirect(url_for('admin.test_management'))
            
        # 获取特定的提交记录
        submission = submissions_collection.find_one({'_id': ObjectId(submission_id)})
        if not submission:
            flash('提交记录不存在', 'danger')
            return redirect(url_for('admin.test_management'))
            
        # 处理ObjectId
        exam['_id'] = str(exam['_id'])
        submission['_id'] = str(submission['_id'])
        
        # 将试题和答案配对
        questions_with_answers = []
        for i, question in enumerate(exam['questions']):
            if i >= len(submission['user_answers']):
                continue
                
            user_answer = submission['user_answers'][i]
            
            # 判断答案是否正确
            is_correct = False
            if question['type'] == 'multiple':
                # 多选题：答案是数组
                if isinstance(user_answer, list):
                    is_correct = sorted(user_answer) == sorted(question['correct_answers'])
            elif question['type'] == 'single':
                # 单选题：答案是整数
                if isinstance(user_answer, int):
                    is_correct = user_answer == question['correct_answers'][0]
            else:  # boolean
                # 判断题：答案是布尔值
                if isinstance(user_answer, bool):
                    is_correct = user_answer == question['correct_answers'][0]
                
            answer_info = {
                'user_answer': user_answer,
                'is_correct': is_correct
            }
            
            questions_with_answers.append((question, answer_info))
            
        return render_template(
            'admin/test_detail.html',
            exam=exam,
            submission=submission,
            questions_with_answers=questions_with_answers
        )
        
    except Exception as e:
        print(f"Error in test_detail: {str(e)}")  # 错误日志
        flash('查看试卷详情时出错', 'danger')
        return redirect(url_for('admin.test_management'))

@admin_bp.route('/logout')
def logout():
    session.clear()
    flash('您已成功退出登录', 'success')
    return redirect(url_for('admin.login'))
